package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"strconv"
	"strings"
)

type CourseCommentController struct {
	BaseController
}

func (u *CourseCommentController) Prepare() {
	u.BaseController.Prepare()
	u.checkAuthor("DataGrid")
}

func (u *CourseCommentController) Index() {
	u.checkLogin()
	u.Data["pageTitle"] = "评论列表"
	u.ActiveSidebarUrl()
	u.Data["canDelete"] = u.checkActionAuthor(u.controllerName, "Delete")
	u.Data["canAudit"] = u.checkActionAuthor(u.controllerName, "Audit")
	u.setTpl("comment/index")
}

func (u *CourseCommentController) DataGrid() {
	var params models.CommentQueryParam
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)
	fmt.Println(string(u.Ctx.Input.RequestBody))

	jsonStu, err := json.Marshal(params)
	if err != nil {
		fmt.Println("生成json字符串错误")
	}
	fmt.Println(string(jsonStu))

	data, total := models.CommentPageList(&params)
	u.BootstrapJson(total, data)
}

func (u *CourseCommentController) Audit() {
	status, _ := u.GetInt("status", 0)
	str := u.GetString("ids")
	ids := make([]int, 0, len(str))

	for _, item := range strings.Split(str, ",") {
		if id, err := strconv.Atoi(item); err == nil {
			ids = append(ids, id)
		}
	}

	query := orm.NewOrm().QueryTable(models.CommentTBName())
	if _, err := query.Filter("id__in", ids).Update(orm.Params{"status": status}); err == nil {
		u.jsonResult(enums.JRCodeSuccess, fmt.Sprintf("更新成功"), 0)
	} else {
		u.jsonResult(enums.JRCodeFailed, "删除失败", 0)
	}
}

func (u *CourseCommentController) Delete() {
	str := u.GetString("ids")
	ids := make([]int, 0, len(str))

	for _, item := range strings.Split(str, ",") {
		if id, err := strconv.Atoi(item); err == nil {
			ids = append(ids, id)
		}
	}

	query := orm.NewOrm().QueryTable(models.CommentTBName())
	if _, err := query.Filter("id__in", ids).Delete(); err == nil {
		u.jsonResult(enums.JRCodeSuccess, fmt.Sprintf("删除成功"), 0)
	} else {
		u.jsonResult(enums.JRCodeFailed, "删除失败", 0)
	}
}
